package com.mingtu.guards.activity;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.callback.StringDialogCallback;
import com.hjq.gson.factory.GsonFactory;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.decoration.LRSpaceItemDecoration;
import com.mingtu.common.decoration.TopSpaceItemDecoration;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.GridSpacingItemDecoration;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.ScreenUtils;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.InfrareDequiAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.InfraredDequiBean;
import com.mingtu.guards.utils.MyConstant;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

import static com.mingtu.guards.utils.MyConstant.ItemDecorationSpaces;
import static com.mingtu.guards.utils.MyConstant.animationType;
import static com.mingtu.guards.utils.MyConstant.isFirstOnly;
import static com.mingtu.guards.utils.MyConstant.isOpenLoadAnimation;

public class InfrareDequipmentActivity extends MyBaseActivity {

    @BindView(R.id.recycler_view)
    RecyclerView recycler;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;
    private int currentPage = 1;
    private boolean isLoadMore = true;
    private InfrareDequiAdapter infrareDequiAdapter;
    private int checkPosition;
    private List<String> deptIdList = new ArrayList<>();
    private List<String> deptNameList = new ArrayList<>();
    private String[] deptNameArray;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_infrare_dequipment;
    }

    @Override
    protected void initView() {
        super.initView();
        setModuleTitle("红外设备管理");
    }

    @Override
    protected void initData() {
        if (ScreenUtils.isTablet()) {
            GridLayoutManager manager1 = new GridLayoutManager(context, 2);
            recycler.setLayoutManager(manager1);
            recycler.addItemDecoration(new GridSpacingItemDecoration(2, SizeUtils.dp2px(ItemDecorationSpaces), true));
        } else {
            LinearLayoutManager manager1 = new LinearLayoutManager(context);
            recycler.setLayoutManager(manager1);
            recycler.addItemDecoration(new TopSpaceItemDecoration());
            recycler.addItemDecoration(new BottomSpaceItemDecoration());
            recycler.addItemDecoration(new LRSpaceItemDecoration());
        }
        infrareDequiAdapter = new InfrareDequiAdapter(context);
        if (isOpenLoadAnimation) {
            infrareDequiAdapter.isFirstOnly(isFirstOnly);
            infrareDequiAdapter.openLoadAnimation(animationType);
        }
        infrareDequiAdapter.setEmptyView(new EmptyDataLayout(context));
        recycler.setAdapter(infrareDequiAdapter);
        infrareDequiAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                InfraredDequiBean.DataBean.ListBean listBean = infrareDequiAdapter.getData().get(position);
                String cameraName = listBean.getCameraName() + "";
                if (!StringUtils.isEmpty(cameraName)) {
                    Bundle bundle = new Bundle();
                    bundle.putString("cameraName", cameraName);
                    IntentUtils.getInstance().readyGo(InfrareDequipmentActivity.this, InfraredRecordPictureActivity.class, bundle);
                } else {
                    ToastUtils.showLong(getResources().getString(R.string.data_error));
                }
            }
        });
        infrareDequiAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                InfraredDequiBean.DataBean.ListBean listBean = infrareDequiAdapter.getData().get(position);
                String lngStr = listBean.getLongitude();
                String latStr = listBean.getLatitude();
                switch (view.getId()) {
                    case R.id.layout_nav:
                        Bundle bundle = new Bundle();
                        bundle.putString("lng", lngStr);
                        bundle.putString("lat", latStr);
                        bundle.putBoolean("isFire", false);
                        IntentUtils.getInstance().readyGo(ActivityUtils.getTopActivity(), NaviMapActivity.class, bundle);

                        break;
                }
            }
        });

    }

    @Override
    protected void getData() {
        initListener();
        getCameraDeptList();
        getDequiList(1);
    }

    @Override
    protected void onClickTitlebarRight(View view) {
        super.onClickTitlebarRight(view);
        showDeptPop();
    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
                currentPage = 1;
                getDequiList(1);
            }
        });
    }

    private void initLoadMoreListener() {
        srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(infrareDequiAdapter.getData(), Constant.PAGE_SIZE);
                    getDequiList(currentPage);
                }
                srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    /**
     * 设备列表
     */
    private void getDequiList(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        if (deptIdList.size() > 0) {
            String deptId = deptIdList.get(checkPosition);
            if(!StringUtils.isEmpty(deptId)){
                hashMap.put("deptId", Integer.parseInt(deptId));
            }
        }
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_INF_DEQUI_LIST)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            InfraredDequiBean infraredDequiBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                infraredDequiBean = new InfraredDequiBean();
                                infraredDequiBean = gson.fromJson(result, InfraredDequiBean.class);
                                List<InfraredDequiBean.DataBean.ListBean> dataBeans = infraredDequiBean.getData().getList();
                                try {
                                    if (dataBeans != null) {
                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            infrareDequiAdapter.replaceData(dataBeans);
                                        } else {
                                            infrareDequiAdapter.addData(dataBeans);
                                        }
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));
                            }
                        }
                    }
                });
    }

    /**
     * 获取部门数据
     */
    private void getCameraDeptList() {
        OkGo.<String>post(MyConstant.POST_INF_DEPT_LIST)
                .tag(this)
                .upJson("")
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            JSONObject data = jsonObject.getJSONObject("data");
                            for (Map.Entry entry : data.entrySet()) {
                                try {
                                    String key = String.valueOf(entry.getKey());
                                    String value = data.getString(key);
                                    deptIdList.add(key);
                                    deptNameList.add(value);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            deptNameArray = new String[deptNameList.size() + 1];
                            deptNameArray[0] = "全部";
                            for (int i = 0; i < deptNameList.size(); i++) {
                                deptNameArray[i + 1] = deptNameList.get(i);
                            }

                            deptIdList.add(0, null);
                            if (deptNameArray != null && deptNameArray.length > 1) {
                                showTopRightImg(R.mipmap.icon_filte_white2);
                            }
                        }
                    }
                });
    }

    /**
     * 显示保护区列表
     */
    public void showDeptPop() {
        new XPopup.Builder(ActivityUtil.getTopActivity())
                .hasShadowBg(true)
                .maxHeight(ScreenUtils.getScreenHeight() / 2)
                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                .asCenterList("请选择部门", deptNameArray,
                        null, checkPosition,
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                checkPosition = position;
                                getDequiList(1);
                            }
                        }).show();

    }

}